<?php
namespace app\common\validate;

use think\Validate;

class ShippingTemplate extends Validate
{
    // 验证规则
    protected $rule = [
        'name' => 'require|max:100',
        'type' => 'require|in:1,2',
        'is_free_shipping' => 'require|in:0,1',
        'rules' => 'require|array|checkRules',
    ];

    // 错误提示信息
    protected $message = [
        'name.require' => '模板名称不能为空',
        'name.max' => '模板名称不能超过100个字符',
        'type.require' => '计费类型不能为空',
        'type.in' => '计费类型值不正确',
        'is_free_shipping.require' => '是否包邮不能为空',
        'is_free_shipping.in' => '是否包邮值不正确',
        'rules.require' => '运费规则不能为空',
        'rules.array' => '运费规则必须是数组',
    ];

    // 自定义验证规则 - 验证rules数组
    protected function checkRules($value)
    {
        if (empty($value)) {
            return '至少需要一个运费规则';
        }

        $subValidator = new Validate();
        $subValidator->rule([
            'region_ids' => 'require|regex:/^\d+(,\d+)*$/',
            'region_names' => 'require',
            'first_unit' => 'require|number|gt:0',
            'first_price' => 'require|float|egt:0',
            'continue_unit' => 'require|number|gt:0',
            'continue_price' => 'require|float|egt:0',
        ]);

        foreach ($value as $rule) {
            if (!$subValidator->check($rule)) {
                return $subValidator->getError();
            }
        }

        return true;
    }

    // 场景验证
    protected $scene = [
        'create' => ['name', 'type', 'is_free_shipping', 'rules'],
        'update' => ['name', 'type', 'is_free_shipping', 'rules'],
    ];
}